import express from 'express'
import cors from 'cors'
import mapService from './services/mapService.js'

const app = express()
const PORT = 3000

app.use(express.json())
app.use(cors({
  origin: 'http://localhost:5173'
}))

// 设置代理路由
app.get('/api/geocoder', async (req, res) => {
  try {
    const address = req.query.address
    const data = await mapService.geocoder(address)
    res.status(200).json(data)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

app.get('/api/distance', async (req, res) => {
  try {
    const { from, to } = req.query
    const data = await mapService.distance(from, to)
    res.status(200).json(data)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

app.get('/api/place', async (req, res) => {
  try {
    const { keyWord } = req.query
    const data = await mapService.placeSuggestion(keyWord)
    res.status(200).json(data)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

app.get('/api/search', async (req, res) => {
  try {
    const { keyword } = req.query
    const data = await mapService.placeSearch(keyword)
    res.status(200).json(data)
  } catch (error) {
    res.status(500).json({ error: error.message })
  }
})

app.listen(PORT, () => {
  console.log(`代理服务器运行在 http://localhost:${PORT}`)
})